package com.gjp.jooqspringboot.dao;

import com.gjp.jooqspringboot.bean.User;
import com.gjp.jooqspringboot.jooq.tables.TbUser;
import com.gjp.jooqspringboot.jooq.tables.records.TbUserRecord;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Gjp on 2018/7/25.
 */
@Repository
public class UserDao {

	@Autowired
	DSLContext create;

	public User insert(User user) {
		TbUserRecord tbUserRecord = create.newRecord(TbUser.TB_USER);
		tbUserRecord.setUsername(user.getUsername());
		tbUserRecord.setSex(user.getSex());
		tbUserRecord.setAge(user.getAge());
		tbUserRecord.insert();    //调用insert
		user.setId(tbUserRecord.getId());
		return user;
	}

	public User update(User user) {
		TbUserRecord tbUserRecord = create.newRecord(TbUser.TB_USER);
		tbUserRecord.setId(user.getId());    //传入id
		tbUserRecord.setUsername(user.getUsername());
		tbUserRecord.setSex(user.getSex());
		tbUserRecord.setAge(user.getAge());
		tbUserRecord.update();    //调用update
		return user;
	}

	public boolean delete(User user) {
		return create
				.deleteFrom(TbUser.TB_USER)
				.where(TbUser.TB_USER.ID.eq(user.getId()))
				.execute() > 0 ? true : false;
	}

	public User selectById(User user) {
		user = create
				.selectFrom(TbUser.TB_USER)
				.where(TbUser.TB_USER.ID.eq(user.getId()))
				.fetchInto(User.class).get(0);
		return user;
	}

	public List<User> selectAll() {
		return create
				.selectFrom(TbUser.TB_USER)
				.fetchInto(User.class);
	}

	public List<User> selectPage(Integer page, Integer size) {
		return create
				.selectFrom(TbUser.TB_USER)
				.limit(size).offset((page - 1) * size)
				.fetchInto(User.class);
	}

	/**
	 * 如果没发生异常，则数据库中的数据，ID为1 3的将会删除，ID为5的数据username则为111
	 * 如果发生异常，数据库数据还是原样
	 * @return
	 */
	public String transcationTest() {
		create.transaction(configuration -> {
			create
					.update(TbUser.TB_USER)
					.set(TbUser.TB_USER.USERNAME,"111")
					.where(TbUser.TB_USER.ID.in(1,3,5))
					.execute();
			create
					.deleteFrom(TbUser.TB_USER)
					.where(TbUser.TB_USER.ID.in(1,3))
					.execute();
			int i = 1/0;
		});
		return "ok";
	}
}
